/**
 * 问答面板组件
 * 引导式问答界面，支持上一题/下一题，跳过，重新生成
 */
import React, { useState, useEffect } from 'react';
import { Card, Input, Button, Space, Progress, message, Tooltip, Tag, Alert, Collapse } from 'antd';
import {
  ArrowLeftOutlined,
  ArrowRightOutlined,
  ReloadOutlined,
  QuestionCircleOutlined,
  BulbOutlined,
  BookOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import { useBrainstormStore } from '@/stores/brainstorm.store';
import { brainstormService } from '@/services/brainstorm.service';
import { debounce } from '@/utils/brainstorm-helpers';
import './style.css';

const { TextArea } = Input;
const { Panel } = Collapse;

export interface QuestionPanelProps {
  onComplete?: () => void;
}

export const QuestionPanel: React.FC<QuestionPanelProps> = ({ onComplete }) => {
  const { currentSession, updateSession } = useBrainstormStore();
  const [currentIndex, setCurrentIndex] = useState(0);
  const [answer, setAnswer] = useState('');
  const [loading, setLoading] = useState(false);
  const [showHints, setShowHints] = useState(true);

  const questions = currentSession?.questions || [];
  const currentQuestion = questions[currentIndex];
  const progress = questions.length > 0 ? ((currentIndex + 1) / questions.length) * 100 : 0;

  // 加载当前问题的答案
  useEffect(() => {
    if (currentQuestion) {
      setAnswer(currentQuestion.answer || '');
    }
  }, [currentQuestion]);

  // 自动保存答案（防抖3秒）
  const autoSave = debounce(async (questionId: string, answerText: string) => {
    if (!currentSession) return;

    try {
      await brainstormService.saveAnswer(currentSession.id, questionId, answerText);
    } catch (error) {
      console.error('Auto save failed:', error);
    }
  }, 3000);

  const handleAnswerChange = (value: string) => {
    setAnswer(value);

    // 更新Store
    if (currentQuestion && currentSession) {
      const updatedQuestions = questions.map((q) =>
        q.id === currentQuestion.id ? { ...q, answer: value, skipped: false } : q
      );
      updateSession({ questions: updatedQuestions });
    }

    // 自动保存
    if (currentQuestion) {
      autoSave(currentQuestion.id, value);
    }
  };

  const handleSelectExample = (example: string) => {
    const currentAnswer = answer.trim();
    const newAnswer = currentAnswer
      ? `${currentAnswer}\n${example}`
      : example;
    handleAnswerChange(newAnswer);
    message.success('已添加到回答中');
  };

  const handleNext = () => {
    if (currentIndex < questions.length - 1) {
      setCurrentIndex(currentIndex + 1);
    } else {
      // 完成所有问题
      if (onComplete) {
        onComplete();
      }
    }
  };

  const handlePrevious = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    }
  };

  const handleSkip = () => {
    if (!currentQuestion || !currentSession) return;

    // 标记为跳过
    const updatedQuestions = questions.map((q) =>
      q.id === currentQuestion.id ? { ...q, skipped: true, answer: '' } : q
    );
    updateSession({ questions: updatedQuestions });

    message.info('已跳过当前问题');
    handleNext();
  };

  const handleRegenerate = async () => {
    if (!currentQuestion || !currentSession) return;

    setLoading(true);
    try {
      const newQuestion = await brainstormService.generateQuestions(currentSession.id, 1);

      if (newQuestion.length > 0) {
        // 替换当前问题
        const updatedQuestions = questions.map((q, index) =>
          index === currentIndex ? newQuestion[0] : q
        );
        updateSession({ questions: updatedQuestions });
        setAnswer('');
        message.success('已生成新问题');
      }
    } catch (error) {
      message.error('重新生成失败');
      console.error('Regenerate question failed:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!currentQuestion) {
    return (
      <div className="question-panel empty">
        <Card>
          <p>暂无问题，请先创建会话</p>
        </Card>
      </div>
    );
  }

  return (
    <div className="question-panel">
      {/* 进度条 */}
      <div className="progress-bar">
        <Progress
          percent={progress}
          showInfo={false}
          strokeColor={{
            '0%': '#1890ff',
            '100%': '#52c41a',
          }}
          strokeWidth={8}
        />
        <div className="progress-text">
          问题 {currentIndex + 1} / {questions.length}
        </div>
      </div>

      {/* 问题卡片 */}
      <Card className="question-card" bordered={false}>
        <div className="question-header">
          <div className="question-type">
            {currentQuestion.purpose === 'audience' && '🎯 目标读者'}
            {currentQuestion.purpose === 'viewpoint' && '💡 核心观点'}
            {currentQuestion.purpose === 'material' && '📚 素材来源'}
            {currentQuestion.purpose === 'style' && '✨ 文章风格'}
            {currentQuestion.purpose === 'goal' && '🎁 期望效果'}
          </div>
          {currentQuestion.skipped && (
            <span className="skipped-badge">已跳过</span>
          )}
        </div>

        <div className="question-text">
          {currentQuestion.text}
        </div>

        {currentQuestion.explanation && (
          <div className="question-explanation">
            <QuestionCircleOutlined style={{ marginRight: 6 }} />
            <span className="explanation-label">为什么问这个问题：</span>
            {currentQuestion.explanation}
          </div>
        )}

        {/* 智能提示区域 */}
        {showHints && (currentQuestion.hints || currentQuestion.examples || currentQuestion.tips) && (
          <div className="question-hints-section">
            <Collapse defaultActiveKey={['hints']} ghost>
              <Panel
                header={
                  <Space>
                    <BulbOutlined style={{ color: '#faad14' }} />
                    <span>智能提示与参考</span>
                  </Space>
                }
                key="hints"
                className="hints-panel"
              >
                {/* 提示要点 */}
                {currentQuestion.hints && currentQuestion.hints.length > 0 && (
                  <div className="hints-block">
                    <div className="hints-label">
                      <BookOutlined /> 思考方向
                    </div>
                    <div className="hints-content">
                      {currentQuestion.hints.map((hint, index) => (
                        <Tag key={index} className="hint-tag">
                          {hint}
                        </Tag>
                      ))}
                    </div>
                  </div>
                )}

                {/* 参考示例 */}
                {currentQuestion.examples && currentQuestion.examples.length > 0 && (
                  <div className="hints-block">
                    <div className="hints-label">
                      <ThunderboltOutlined /> 参考示例（点击可快速添加）
                    </div>
                    <div className="examples-list">
                      {currentQuestion.examples.map((example, index) => (
                        <div
                          key={index}
                          className="example-item"
                          onClick={() => handleSelectExample(example)}
                        >
                          <span className="example-number">{index + 1}</span>
                          <span className="example-text">{example}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* 写作技巧 */}
                {currentQuestion.tips && currentQuestion.tips.length > 0 && (
                  <div className="hints-block">
                    <div className="hints-label">
                      <BulbOutlined /> 写作技巧
                    </div>
                    <div className="tips-list">
                      {currentQuestion.tips.map((tip, index) => (
                        <div key={index} className="tip-item">
                          {tip}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </Panel>
            </Collapse>
          </div>
        )}

        <div className="answer-input">
          <TextArea
            value={answer}
            onChange={(e) => handleAnswerChange(e.target.value)}
            placeholder="请输入你的答案..."
            rows={6}
            maxLength={1000}
            showCount
            autoFocus
          />
        </div>

        <div className="question-actions">
          <Space size={12}>
            <Button
              icon={<ArrowLeftOutlined />}
              onClick={handlePrevious}
              disabled={currentIndex === 0}
            >
              上一题
            </Button>

            <Button onClick={handleSkip} disabled={loading}>
              跳过
            </Button>

            <Tooltip title="重新生成一个不同的问题">
              <Button
                icon={<ReloadOutlined />}
                onClick={handleRegenerate}
                loading={loading}
              >
                换个问题
              </Button>
            </Tooltip>

            <Button
              type="primary"
              icon={<ArrowRightOutlined />}
              onClick={handleNext}
              disabled={loading}
            >
              {currentIndex < questions.length - 1 ? '下一题' : '完成'}
            </Button>
          </Space>
        </div>
      </Card>

      {/* 底部提示 */}
      <div className="panel-tip">
        💡 提示：答案会自动保存，点击示例可快速添加到回答中
      </div>
    </div>
  );
};
